package com.cicadamob.contact.api.group.asynctask;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.cicadamob.contact.api.Utils.ContactConfig;
import com.cicadamob.contact.api.Utils.StringUtil;
import com.cicadamob.contact.api.Utils.Logger.AppLogger;
import com.cicadamob.contact.api.Utils.NetWork.HttpRequestCallBack;
import com.cicadamob.contact.api.Utils.NetWork.HttpUtil;
import com.cicadamob.contact.api.Utils.NetWork.NetWorkUtil;
import com.cicadamob.contact.api.Utils.NetWork.HttpUtil.RequestMethod;
import com.cicadamob.contact.api.group.bean.ResultModel;
import com.cicadamob.contact.api.group.dao.Group_Db_Dao;
import com.cicadamob.contact.api.group.http.Http_Group_Util;
import com.cicadamob.contact.api.group.http.JsonParseUtil;
import com.cicadamob.contact.api.service.Contact;
import com.cicadamob.contact.api.service.ServerUrl;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

public class LoadGroupMember implements Runnable {
	private Handler mHandler;
	private int what;
	private Context mContext;
	private String groupID;
	private Group_Db_Dao dbHelper;
	private boolean isUpdateFromNet;
	private boolean onlyInstalled;

	public LoadGroupMember(Handler mHandler,int what,Context mContext,String groupID,boolean isUpdateFromNet,boolean onlyInstalled){
		this.mHandler=mHandler;
		this.what=what;
		this.mContext=mContext;
		this.groupID=groupID;
		this.isUpdateFromNet=isUpdateFromNet;
		this.onlyInstalled=onlyInstalled;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		dbHelper=Group_Db_Dao.getInstance(mContext);;
		ResultModel resultMode = new ResultModel();
		if (!NetWorkUtil.isConnected(mContext)) {
			resultMode.setRetcode(0);
			ArrayList<Contact> sContacts=null;
			if(onlyInstalled){
				sContacts=(ArrayList<Contact>) dbHelper.queryAllMemberByGroupIdForSelect(groupID, onlyInstalled);
			}else{
				sContacts= (ArrayList<Contact>) dbHelper
						.queryAllMemberByGroupId(groupID);
			}
			 
			
			resultMode.setResultData(sContacts);
			sendMessage(resultMode);
			return ;// 网络不异常
		}
		
		if(!isUpdateFromNet){
			resultMode.setRetcode(0);
			ArrayList<Contact> sContacts = (ArrayList<Contact>) dbHelper
					.queryAllMemberByGroupId(groupID);
			resultMode.setResultData(sContacts);
			sendMessage(resultMode);
			return;
		}
		
		
		mHandler.post(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String xmlData=Http_Group_Util.get_getGroupMemberXML(groupID,dbHelper.getQueryMemberTimeStamp(groupID));
				Map<String, String> requestMap=new HashMap<String, String>();
				requestMap.put(HttpUtil.XML, xmlData);
				AppLogger.writeLogToFile(mContext, ContactConfig.DIRECTORY+"/httpGroupLog", "msg_group", "发送报文  url =" + ServerUrl.GET_GROUP_MEMBER
			    		+"\r\n xml ="+xmlData, true);
				HttpUtil.HttpRequest(mContext, RequestMethod.POST, ServerUrl.GET_GROUP_MEMBER, true,requestMap, new HttpRequestCallBack<String>(){

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// TODO Auto-generated method stub
						AppLogger.writeLogToFile(mContext, ContactConfig.DIRECTORY+"/httpGroupLog", "msg_group", "响应报文  url =" + ServerUrl.GET_GROUP_MEMBER
					    		+"\r\n xml ="+responseInfo.result, true);	
						doResult(responseInfo.result);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// TODO Auto-generated method stub
						ResultModel resultMode = new ResultModel();
						resultMode.setRetcode(-9);
						sendMessage(resultMode);
					}
					
				});
			}
		});
		
	}
	
	private void sendMessage(ResultModel mResult){
		mHandler.obtainMessage(what, mResult).sendToTarget();
	}
	
	private void doResult(String result){
		ResultModel resultMode = new ResultModel();
		if (result == null) {
			resultMode.setRetcode(-10);
			ArrayList<Contact> sContacts = (ArrayList<Contact>) dbHelper
					.queryAllMemberByGroupId(groupID);
			resultMode.setResultData(sContacts);
			sendMessage(resultMode);
			return ;
		}
		
		ResultModel resultmodel = Http_Group_Util.parseResult(result);
		
		if (resultmodel.getRetcode() == 0) {
			String SqlStr = resultmodel.getGroupmembers();
			dbHelper.updateVersion(groupID, resultmodel.getLastupdatetime());
			if (!StringUtil.isEmpty(SqlStr)) {
				dbHelper.delTempMember(groupID);
				dbHelper.executesql(JsonParseUtil
						.jsonTOStringMemberList(SqlStr));
			} 
		} 

		if (resultmodel.getRetcode() == 3) {
			dbHelper.delGroupById(groupID);
		} else {
			ArrayList<Contact>	sContacts = (ArrayList<Contact>) dbHelper
					.queryAllMemberByGroupId(groupID);
			resultmodel.setResultData(sContacts);
		}
		sendMessage(resultmodel);
	}

}
